# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 10:02:25 2017

@author: xuanlei
"""
import encoder_test as et
import encoder_lstm as lstm
import copy_win_data
import encoder_lstm_test
import get_data as dl
import win_data as mvd
import pandas as pd
import tensorflow as tf
from sklearn.cross_validation import train_test_split
import numpy as np
from sklearn.metrics import classification_report
from sklearn.preprocessing import normalize, MaxAbsScaler
import random
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
#==============================================================================
# Global Option
#==============================================================================
feature_list = [0,       1,       2,       3,       4,       5,       6,       7,
             8,       9,      10,      11,      12,      13,      14,      15,
            16,      17,      18,      19,      20,      21,      22,      23,
            24,      25,      26,      27,      28,      29,      30,      31,
            32,      33,      34,      35,      36,      37,      38,      39,
            40,      41]

label_list = 'label'


#==============================================================================
# Hyper-Para Setting
#==============================================================================
input_size = len(feature_list)
cell_size = 21
num_size = 3
LR = 0.001
n_steps = 10
h1_size = 19
h2_size = 25
h3_size = 18
output_size = 1


def test(dft):
    ylabel = []
    dftx = et.encoder_data(xr,dft)
    win = copy_win_data.get_moving_data(dftx,1)
    batch_size = len(win)
    tf.reset_default_graph()
    test_data = encoder_lstm_test.dataframe_to_tensor(win,feature_list)
    ys_label = encoder_lstm_test.dataframe_to_tensor(win, label_list, nm=False).reshape([-1,1])
    ylabel.extend(int(p) for p in ys_label)
    model = lstm.LSTMRNN(n_steps, input_size, output_size, cell_size, h1_size, h2_size, h3_size, LR,num_size, batch_size)
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, 'lstm_para_94_29/para_log')
        with tf.variable_scope('scope', reuse=True):
            feed_dict_test = {model.xs:test_data,
                                   model.keep_prob: np.array(1,  dtype='float32'), model.train_phase: False}
            vail_predict = sess.run(model.pred, feed_dict=feed_dict_test)
            result = []
            for item in vail_predict:
                if item >= 0.3:
                    result.append(1)
                else:
                    result.append(0)   

            ind = dft.iloc[0:len(result),:].index
            tex = pd.DataFrame(result,index = ind,columns = ['label'])
            tex['pre'] = vail_predict
            tex['real_label'] = ys_label
            print(".................>>>>...>")
            print(classification_report([int(x) for x in ys_label], result))
            encoder_lstm_test.confusion_matrix_plot_matplotlib(result,list(ys_label),cmap=plt.cm.tab10_r)
            
#            print(".................>>>>...>")
#    print('----------->Samples Test process has completed!<------------------')
    return tex

def plots(df,name,l,col ='label'):
    df.loc[:,col].plot(subplots=1,use_index = 1,label=name+'号'+l+'风机',color='r')
    plt.legend(loc=1)
    plt.title('01随时间变化')
    plt.xlabel('时间区间（连续的数据条数）')
    plt.ylabel('预测标签')


def start_test():
    err_wtno = [3,18,20,2,19]
    run_wtno = [11,12,10,13]
    nomal_run_wtno = [8,10,17]
    
#    test_err = [result_err_e[i] for i in [3,18,20,2,19]]
#    test_run = [result_err_r[i] for i in [11,12,10,13]]
#    test_nomal_run = [result_run[i] for i in [8,10,17]]
    
    print('故障风机测试结果如下，共5台...')
    for wtno in err_wtno:
        print('now test {0}'.format(err_table[wtno][0]))
        globals()['test_err_'+err_table[wtno][0]] = test(result_err_e[wtno])
        plots(globals()['test_err_'+err_table[wtno][0]],'故障',err_table[wtno][0])
        print(".................<<<<...<")
    print('5台故障风机测试结束...')
    print('开始测试故障风机正常数据段，共4台...')
    for wtno in run_wtno:
        print('now test {0}'.format(err_table[wtno][0]))
        globals()['test_err_r_'+err_table[wtno][0]] = test(result_err_r[wtno])
        plots(globals()['test_err_r_'+err_table[wtno][0]],'故障修复',err_table[wtno][0])
        print(".................<<<<...<")
    print('4台故障风机正常数据段测试结束...')
    print('开始测试正常风机，共3台...')
    for wtno in nomal_run_wtno:
        print('now test {0}'.format(run_table[wtno][0]))
        globals()['test_run_'+run_table[wtno][0]] = test(result_run[wtno])
        plots(globals()['test_run_'+run_table[wtno][0]],'正常',run_table[wtno][0])
        print(".................<<<<...<")
    print('3台正常风机数据段测试结束...')
    
    
